package utils;

import book.Book;
import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

import static constant.Constant.BORROW_ALL_BOOK_FILE_NAME;

/**
 * Created with IntelliJ IDEA.
 * Description:普通用户借书和还书的工具类
 * User: 87111
 * Date: 2025-08-24
 * Time: 18:14
 */
public class AnalyzingBorrowedBook {
    //将数据写入文件中
    public void writeBorrowBook(PairOfUidAndBookId[] pair, String fileName) {
        //先遍历pair数组里面有多少数据
        int pairNum = 0;
        for (int i = 0; i < pair.length; i++) {
            if(pair[i] != null) {
                pairNum++;
            }
        }
        //将对象转化为字符串
        StringBuilder bookString = new StringBuilder();
        for (int i = 0; i < pairNum; i++) {
            if(pair[i] != null) {
                bookString.append(pair[i].toJson());
            }
            if(i != pairNum - 1) {
                bookString.append("\n");
            }
        }
        FileUtils.writeFile(bookString.toString(), BORROW_ALL_BOOK_FILE_NAME);
    }

    //从文件中读取数据
    public PairOfUidAndBookId[] readBorrowBook(String filName) {
        String fileString = FileUtils.readFile(filName);
        if(fileString == null || fileString.isEmpty()) {
            System.out.println("已借阅书籍列表无数据或者未借过书");
            return null;
        }
        //单个对象字符串
        String[] s = fileString.split("\n");
        //单个对象数组
        PairOfUidAndBookId[] pair = new PairOfUidAndBookId[s.length];
        for (int i = 0; i < s.length; i++) {
            PairOfUidAndBookId pair1 = new PairOfUidAndBookId();
            String[] s2 = s[i].split(",");
            pair1.setUserId(Integer.parseInt(s2[0]));
            pair1.setBookId(Integer.parseInt(s2[1]));
            pair[i] = pair1;
        }
        return pair;
    }
}
